from ldap3 import Server, Connection, ALL, SUBTREE, ServerPool, ALL_ATTRIBUTES, NTLM, Tls
from settings import config
from apps.account.models import LoonUser
from ldap3.utils.dn import safe_rdn

import json
import datetime


class MyLdap(object):

    def __init__(self, ldap_server_pool, admin_dn, admin_password, search_bash):
        self.LDAP_SERVER_POOL = [ldap_server_pool]  # 域控服务器ip地址

        self.ADMIN_DN = admin_dn  # 拥有查询权限的域账号
        self.ADMIN_PASSWORD = admin_password  # 对应的密码
        self.SEARCH_BASE = search_bash

    def get_conn(self):
        ldap_server_pool = ServerPool(self.LDAP_SERVER_POOL)
        conn = Connection(ldap_server_pool, user=self.ADMIN_DN, password=self.ADMIN_PASSWORD,
                          check_names=True, lazy=False, raise_exceptions=False, read_only=False)
        conn.open()
        conn.bind()

        return conn

    def ldap_login(self, username, password):

        conn = self.get_conn()

        res = conn.search(
            search_base=self.SEARCH_BASE,
            search_filter=f'(cn={username})',
            search_scope=SUBTREE,
        )
        # print('res:', res)
        if res:
            # username_suffix = self.ADMIN_DN.split("@")[1]
            # print('user:', f"{username}", 'password:', password)
            # conn2 = Connection(self.LDAP_SERVER_POOL, user=f"{username}" + "@bybit-testdev.com", password=password,
            conn2 = Connection(self.LDAP_SERVER_POOL, user=f"{username}" + "@bybit.com", password=password,
                               check_names=True, lazy=False, raise_exceptions=False)
            conn2.bind()
            # print('bind结果：', conn2.result)
            if conn2.result['description'] == 'success':  # 表示验证成功
                return True
            else:
                return False
        else:
            return False


user_dict = {'first_name': 'givenName', 'last_name': 'sn', 'alias': 'sn', 'email': 'mail', 'username': 'cn'}
mldap = MyLdap(config.MY_LDAP_SERVER_URI, config.MY_LDAP_BIND_DN, config.MY_LDAP_BIND_PASSWORD,
               config.MY_LDAP_SEARCH_BASE)
# mldap.ldap_sync_user(user_dict)
# print('登录结果:', mldap.ldap_login(username='baozhou7.wang', password='O9I3zPobSosYUz6KpH'))
# mldap.ldap_login(username='pounds.zeng', password='oDjJ6yePzpuLPsPVEZ')
